// pages/profile/subscribe-settings.js
import api from '../../utils/api'

Page({
  data: {
    subscribeEnabled: false,
    loading: true,
    saving: false
  },

  onLoad() {
    this.loadSettings()
  },

  async loadSettings() {
    try {
      this.setData({ loading: true })
      const result = await api.subscription.getSettings()
      // 期望结构：{ user_info: { subscribe_enabled: boolean }, ... }
      let enabled = false
      if (result && result.user_info && typeof result.user_info.subscribe_enabled === 'boolean') {
        enabled = result.user_info.subscribe_enabled
      }
      this.setData({ subscribeEnabled: enabled })
    } catch (e) {
      console.error('获取订阅设置失败:', e)
      wx.showToast({ title: '加载失败', icon: 'none' })
    } finally {
      this.setData({ loading: false })
    }
  },

  async onSubscribeChange(e) {
    const enabled = !!e.detail.value
    // 先更新 UI，提升响应体验
    this.setData({ subscribeEnabled: enabled, saving: true })
    try {
      const data = await api.subscription.update(enabled)
      let finalEnabled = enabled
      if (data && typeof data.subscribe_enabled === 'boolean') {
        finalEnabled = data.subscribe_enabled
      }
      this.setData({ subscribeEnabled: finalEnabled })
      wx.showToast({ title: finalEnabled ? '已开启' : '已关闭', icon: 'success' })
    } catch (err) {
      console.error('更新订阅设置失败:', err)
      // 回滚
      this.setData({ subscribeEnabled: !enabled })
      wx.showToast({ title: '设置失败', icon: 'none' })
    } finally {
      this.setData({ saving: false })
    }
  },

  onPullDownRefresh() {
    const that = this
    this.loadSettings().finally(() => {
      wx.stopPullDownRefresh()
      that.setData({ saving: false })
    })
  }
})